//face.c
#include <Python.h>

// 增加拍照指令和照片路径宏定义
#define WGET_CMD "sudo wget http://192.168.43.90:8080/?action=snapshot -O /tmp/SearchFace.jpg"
#define SEARCHFACE_FILE "/tmp/SearchFace.jpg"

void face_init(void)
{
    Py_Initialize();
    PyObject *sys = PyImport_ImportModule("sys");
    PyObject *path = PyObject_GetAttrString(sys, "path");
    PyList_Append(path, PyUnicode_FromString("."));
}

void face_final(void)
{
    Py_Finalize();
}

double face_category(void)
{
    double result = 0.0; //垃圾分类项目里返回的是字符串人脸识别中返回的是浮点数
    system(WGET_CMD);
    if(0==access(SEARCHFACE_FILE,F_OK))
    {
        return result;
    }
    PyObject *pModule = PyImport_ImportModule("face");
    if (!pModule)
    {
        PyErr_Print();
        printf("Error: failed to load face.py\n");
        goto FAILED_MODULE;
    }
    PyObject *pFunc = PyObject_GetAttrString(pModule, "alibaba_face");
    if (!pFunc)
    {
        PyErr_Print();
        printf("Error: failed to load alibabacloud_face\n");
        goto FAILED_FUNC;
    }
    PyObject *pValue = PyObject_CallObject(pFunc, NULL);
    if (!pValue)
    {
        PyErr_Print();
        printf("Error: function call failed\n");
        goto FAILED_VALUE;
    }
    
    if (!PyArg_Parse(pValue, "d", &result))
    {
        PyErr_Print();
        printf("Error: parse failed");
        goto FAILED_RESULT;
    }
    // printf('result=%lf\n',result);
    // category = (char *)malloc(sizeof(char) * (strlen(result) + 1) );
    // memset(category, 0, (strlen(result) + 1));
    // strncpy(category, result, (strlen(result) + 1));
FAILED_RESULT:
    Py_DECREF(pValue); 
FAILED_VALUE:
    Py_DECREF(pFunc);
FAILED_FUNC:
    Py_DECREF(pModule);
FAILED_MODULE:
    return result;
}

